package com.my.study.algorithm.leetcode;


import java.util.ArrayList;
import java.util.List;

/**
 * 从尾到头打印链表
 * <p>
 *     输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 *     
 * class Solution {
 *     int[] res;
 *     int i = 0;
 *     int j = 0;
 *     public int[] reversePrint(ListNode head) {
 *         solve(head);
 *         return res;
 *     }
 *     public void solve(ListNode head){
 *         if(head == null){
 *             res = new int[i];
 *             return;
 *         }
 *         i++; 
 *         solve(head.next);
 *         res[j] = head.val;
 *         j++;
 *     }
 * }
 * </p>
 * 
 * @author Carlos
 * @version 1.0.0
 * @date 2023/1/3 22:08
 */
public class ReversalPrintLinked {
    
    int[] res;
    int i;
    int j;

    public int[] reversePrint(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;

        List<Integer> resList = new ArrayList<>();
        
        while (null != cur) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        
        if (null != pre) {
            cur = pre;
            while (null != cur) {
                resList.add(cur.val);
                cur = cur.next;
            }
        }
        int[] res = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            res[i] = resList.get(i);
        }
        
        return res;
    }

    public int[] reversePrint1(ListNode head) {
        
        return res;
    }
    
    private void solve(ListNode head) {
        if (null == head) {
            res = new int[i];
            return;
        }
        i++;
        solve(head.next);
        res[j] = head.val;
        j++;
    }
    
    
    
    private static class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public static void main(String[] args) {
        ListNode node3 = new ListNode(3);
        ListNode node2 = new ListNode(2, node3);
        ListNode head = new ListNode(1, node2);

        ReversalPrintLinked reversalPrintLinked = new ReversalPrintLinked();
        int[] ints = reversalPrintLinked.reversePrint(head);
        System.out.println(ints);
    }
    
}
